<script setup>
import {ref, reactive, computed, watch, nextTick} from "vue"; 
import dayjs from "dayjs";
import utils from "@/common/utils/utils.js";

// 测量宽度的 工具 
import { tool } from '@/common/utils/richTextProcessing.js'

// 手机组件
import { DraggableContainer } from "vue3-draggable-resizable";
import Vue3DraggableResizable from "vue3-draggable-resizable";
//default styles
import "vue3-draggable-resizable/dist/Vue3DraggableResizable.css";
import { useStore } from "vuex";

// 默认数据
import { logo_urls_item } from '@/views/shotstack/MixedCutPlatforms/utools/template.js'


// 混剪 公共参数配置
import {
  // 视频截取首帧画面
    captureFirstFrame,
  // 计算可拖拽区域的宽高比例
  calculateDraggableArea
} from "@/common/utils/richTextProcessing.js";

// 仓库
const store = useStore();

const emit = defineEmits(['update_position:obj'])

const props = defineProps({
    // 手机组件是否显示隐藏
    phoneVisible: {
        type: Boolean,
        default: false,
    },
    visible: {
        type: Boolean,
        default: false,
  },

  // 当前编辑的项
  editItem: {
    type: Object,
    default: () => {
        return {}
    }
  },

  // 当前分辨率
  pixel: {
    type: Object,
    default: () => {
        return null
    }
  },

  // 当前素材列表
  images: {
    type: Array,
    default: () => {
        return []
    }
  },

  // 当前选择的图片模板
  image_tpl: {
    type: String,
    default: () => ''
  }

})

// 花字列表
const flowerList = computed(() => {
  return store.state.GraphicTextMixCut.flowerList
});

const state = reactive({
  showImg: true,
  // 当前编辑的项
  editItem:null,
  defaultBgc: '#fff',

  // 当前组 根据图片排版 筛选的 展示的图片
  showImg:[]
})

const editItem = computed({
  get() {
    return props.editItem
  },
  set(val) {
    console.log(val, '修改了!!!!!');
  }
})

// ==================== 控制主标题


// 拖拽节点的宽高
const main_width = ref('100%')
const main_height = ref('100%')
// 存放主标题的宽高
const setMainWH = () => {
  nextTick(() => {    
    // debugger
    let domObj = document.getElementById("main_content");
        // 复制一个元素, 计算宽度
        const data = tool.measureTextWithSpan(domObj, domObj.textContent);
        main_width.value = data.width;
        main_height.value = domObj?.offsetHeight;
  })
}

const textStyle_main = computed(() => {
  let font_size = editItem.value.main.config.font_size;
  // 是否选择了花字
  const findFlower = flowerList.value.find(ele => ele.id == editItem.value.main.config.flower_id)
  let flower = {}
  if (!!findFlower) {
      flower = {
        color: findFlower.fontcolor,
        "-webkit-text-stroke": findFlower.bordercolor ? `1px ${findFlower.bordercolor}` : "",
        background: findFlower?.boxcolor || 'transparent',
    }
  }
  setMainWH()
  return {
    "font-family": editItem.value.main.config.font,
    'font-size': font_size + 'px',
    'text-align': 'left',
    ...flower
  }
})

// ==================== 控制副标题

// 拖拽节点的宽高
const deputy_width = ref('100%')
const deputy_height = ref('100%')
// 存放副标题的宽高
const setDeputyWH = () => {
  nextTick(() => {    
    // debugger
    let domObj = document.getElementById("deputy_content");
        // 复制一个元素, 计算宽度
        const data = tool.measureTextWithSpan(domObj, domObj.textContent);
        deputy_width.value = data.width;
        deputy_height.value = domObj?.offsetHeight;
  })
}

const textStyle_deputy = computed(() => {
  if (!editItem.value.deputy) {
    return {}
  }

  let font_size = editItem.value.deputy.config.font_size;
  // 是否选择了花字
  const findFlower = flowerList.value.find(ele => ele.id == editItem.value.deputy.config.flower_id)
  let flower = {}
  if (!!findFlower) {
      flower = {
        color: findFlower.fontcolor,
        "-webkit-text-stroke": findFlower.bordercolor ? `1px ${findFlower.bordercolor}` : "",
        background: findFlower?.boxcolor || 'transparent',
    }
  }
  setDeputyWH()
  return {
    "font-family": editItem.value.deputy.config.font,
    'font-size': font_size + 'px',
    'text-align': 'left',
    ...flower
  }
})

watch(() => editItem.value.main.content, (nv, ov) => {
  setMainWH()
})

watch(() => editItem.value.deputy?.content, (nv, ov) => {
  setDeputyWH()
})

const background = ref({
  type: "color",
  url: "transparent",
});

const parentBgc = computed(() => {
  let returnVal =
    background.value.type == "color"
      ? {
        background: background.value.url,
      }
      : {
        background: `url(${background.value.url})`,
        'background-repeat': 'no-repeat',
        'background-size': 'contain',
        "backgroundPosition": "center",
      };
  return returnVal
})

// 拖拽背景图
const resizableStyle = computed(() => {
  const sizeData = calculateDraggableArea(
    props.pixel?.w,
    props.pixel?.h
  );
  console.log(sizeData,'父组件大小');
  
  return {
    width: sizeData.draggableWidth + "px",
    height: sizeData.draggableHeight + "px",
    transition: "all 0.3s",
    'z-index': 1,
    overflow: 'hidden',
    position: 'relative',
    background: state.defaultBgc
    // background: `url(https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/20241223/y1fICvVDbmaOW78phxt8C.jpg`+'?v=' + (new Date()).valueOf(),
  };
});

// 背景设置的参数
const bgc = computed(() => {
  const data = null
  if (data?.type == 1) {
    return {
      'background': data.rgba
    }
  } else if (data?.type == 2 || data?.type == 3) {
    let url = data.material_urls[0].url
    return {
      'background': `url(${url})`,
      'background-position': 'center',
      'background-size': 'cover'
    }
  } else {
    return {
      'background': '#000'
    }
  }
});

// 主标题拖动结束修改 x和y的位置
const dragEndHandle_main = (data) => {
  // return;
  console.log("拖拽结束", data);
  emit('update_position',{x: data.x, y: data.y, key:'main'})
};

// 副标题拖动结束修改 x和y的位置
const dragEndHandle_deputy = (data) => {
  // return;
  console.log("拖拽结束", data);
  emit('update_position',{x: data.x, y: data.y, key:'deputy'})
};


// 使用的背景
const useBgc = async () => {

 // 判断使用的背景
 const find = VideoMashup.value.resource_data.find(
    (ele) => ele.material_list.length
  );

  if (!find) return (background.value = { url: "transparent", type: "color" });
  const material = find.material_list[0];

  if (material?.scene_type == "video") {
    const url = await captureFirstFrame(material.material_url);
    
    if (url) {
      background.value = { url, type: "img" };
    } else {
      background.value = "transparent";
      background.value = { url: "transparent", type: "color" };
    }
  } else if (material?.scene_type == "image") {
    const url = material.material_url;
    url
      ? (background.value = { url, type: "img" })
      : (background.value = { url: "transparent", type: "color" });
  } else {
    background.value = { url: "transparent", type: "color" };
  }
};



// 切割数组方法
function getFirstElements(arr, num) {
    if (!Array.isArray(arr)) {
        return [];
    }
    num = num === undefined? arr.length : num;
    num = Math.min(num, arr.length);
    return arr.slice(0, num);
}
/**
* @param {
  * 图片模版 
  * single_image: 单图; 
  * couple_image_9_16: 2图9:16; 
  * couple_image_16_9: 2图16:9;
  * couple_image_1_1: 2图1:1;
  * four_image_9_16: 4图9:16;
  * four_image_1_1: 4图1:1;
* } image_tpl
*  */
const showImgs = computed(() => {
  const image_tpl = props.image_tpl
  const images = props.images
  let arr = []
  if (image_tpl == 'single_image') {
    images?.[0] &&  (arr[0] = images[0])
  } else if (
       image_tpl == 'couple_image_9_16'
    || image_tpl == 'couple_image_16_9'
    || image_tpl == 'couple_image_1_1'
  ) {
    arr = getFirstElements(images, 2)
  } else if (image_tpl == 'four_image_9_16' || image_tpl == 'four_image_1_1') {
    arr = getFirstElements(images, 4)
  }

  
  return arr || []
})

const imgBoxStyle = computed(() => {
  const image_tpl = props.image_tpl
  if (!image_tpl) return {}
  if (image_tpl == 'couple_image_9_16'
    || image_tpl == 'couple_image_16_9'
    || image_tpl == 'couple_image_1_1'
  ) {
    if (showImgs.value.length <= 1) {
      return {
      width:'50%'
    }
    }
  } else if (image_tpl == 'four_image_9_16' || image_tpl == 'four_image_1_1') {
    return {
      display: 'grid',
      'grid-template-columns': `repeat(2, 1fr)`,
      // 'align-content': 'flex-start'
    }
  }

})

defineExpose({
  useBgc,
})

</script>

<template>

          <!-- 手机组件 v-if="props.pixel" 

                      width: 270 + 30 + 'px',
            height: 480 + 47.809 + 'px'

            left: visible ? 'calc((100% - 50%) / 2)' : '-999999px',

          -->
          <div id="logo_phoneConCover" class="phoneConCover_content" :style="{
            opacity: props.phoneVisible ? 1 : 0,
            transition: 'opacity 0.5s',
            width: 360 + 30 + 'px',
            height: 730 + 47.809 + 'px' 
          }">

            <!-- 手机头部 -->
            <div class="mobile-header">
              <div class="time">{{ dayjs().format("HH:mm") }}</div>
              <div class="wife">
                <cu-icon type="icon-xinhao" style="font-size: 12px"></cu-icon>
                <cu-icon type="icon-wife" style="margin: 0 2px; font-size: 14px"></cu-icon>
                <cu-icon type="icon-electricity-full" style="font-size: 14px"></cu-icon>
              </div>
            </div>

            <!-- 素材背景图 -->
            <div class="bgc_content" :style="{
              ...parentBgc,
              'z-index': 1,
              left: 0
            }">
            </div>
            <!-- 底层背景图 -->
            <div class="left_phone_view" :style="{
              ...bgc,
              display: 'flex',
              'justify-content': 'center',
              'align-items': 'center'
            }">
              <DraggableContainer
              id="phone_dom"
              v-if="props.phoneVisible" :style="resizableStyle"
              :referenceLineColor="'white'">
                <!-- lockAspectRatio : 是否锁定比例
                v-model:w="textData.width" v-model:h="textData.height" 
                   v-model:active="ResizableActive"
                -->

                <!-- 主标题 -->
                <Vue3DraggableResizable   
                  v-model:x="editItem.main.config.x"
                  v-model:y="editItem.main.config.y" 
                  v-model:w="main_width" 
                  v-model:h="main_height" 
                  :lockAspectRatio="true"
                  :resizable="false" :draggable="true"
                  :parent="true" @drag-end="dragEndHandle_main"
                  >
                  <p class="editor_content" :style="{...textStyle_main}">{{ editItem.main.content }}</p>
                </Vue3DraggableResizable>
                <p id="main_content" class="editor_content" :style="{...textStyle_main, opacity: 0}">{{ editItem.main.content }}</p>

                <!-- 副标题 -->
                 <template v-if="editItem.deputy">
                   <Vue3DraggableResizable   
                     v-model:x="editItem.deputy.config.x"
                     v-model:y="editItem.deputy.config.y" 
                     v-model:w="deputy_width" 
                     v-model:h="deputy_height" 
                     :lockAspectRatio="true"
                     :resizable="false" :draggable="true"
                     :parent="true" @drag-end="dragEndHandle_deputy"
                     >
                     <p class="editor_content" :style="{...textStyle_deputy}">{{ editItem.deputy.content }}</p>
                   </Vue3DraggableResizable>
                   <p id="deputy_content" class="editor_content" :style="{...textStyle_deputy, opacity: 0}">{{ editItem.deputy.content }}</p>
                 </template>

                 <template  v-if="Array.isArray(showImgs) && showImgs.length">
                  <div class="phone_img_box"  :style="{...imgBoxStyle,  }">
                    <!--  + `?timestamp=${Date.now()})` -->
                  <div        
                    v-for="item in showImgs"
                  :key="item.id"
                  class="img_content"
                  :style="{
                    background: `url(${item.material_url}`,
                    'background-repeat': 'no-repeat',
                    'background-size': 'cover',
                  }"  
                    >
                    </div>
                  </div>
                 </template>
              </DraggableContainer>
            </div>

          </div>
</template>


<style lang="less" scoped>

  // 手机样式
  .phoneConCover_content {
    // width: 360px;
    // height: 730px;
    // position: fixed;
    // top: 50%;
    // left: calc(calc(100% - 50%) / 2);
    // transform: translate(-50%, -50%);
    // flex-direction: column;
    // overflow: hidden;
    border-radius: 20px;
    background-color: #000;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: content-box;
    position: relative;

    .mobile-header {
      height: 44px;
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);
      background: black;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fff;
      padding: 10px 10px;
      overflow: hidden;
    }

    // 背景图
    .bgc_content {
      position: absolute;
      top: 43.5px;
      left: 0;
      width: 100%;
      height: calc(100% - 88px);
      background-repeat: no-repeat;
      background-size: contain;
      // background-size: 100%;
      // height: 100%;
      /* 添加这一行 */
      pointer-events: none;
      z-index: 2;
    }

    .left_phone_view {
      overflow: hidden;
      position: relative;
      width: 100%;
      height: calc(100% - 88px);
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);

      .editor_content {
        margin-bottom: 0;
        border: none;
        resize: none;
        height: auto;
        display: inline-block;
        // overflow: hidden;
        // 禁止选中
        pointer-events: none;
        // 换行显示
        white-space: pre-wrap;
        // 不考虑连贯性, 强制换行
        word-break: break-all;
      }

      .phone_img_box{
        position: absolute; 
        left: 0;
        top: 0;
        z-index: -1;
        width: 100%;
        height: 100%;
        display: flex;
        flex-wrap: wrap;

        .img_content{
          flex: 1;
          height: 100%;
          width: 100%;
        }

      }
    }

    // 手机下方的控制按钮
    .bottom_View_control {
      position: absolute;
      bottom: -50px;
      left: 50%;
      z-index: 5;
      transform: translate(-50%, 0);
      display: flex;
    }
  }

</style>